/**
 * Hermit 套件库，页面布局设计器
 */
Rsd.define('Rsd.tool.HermitPageLayouter', {
    extend: 'Rsd.container.Dialog',
    xtype: 'hermit-part-selector',
    requires: [
        'Rsd.hermit.sections.AdsViewPart',
        'Rsd.hermit.sections.CollectionPart',
        'Rsd.hermit.sections.CopyrightViewPart',
        'Rsd.hermit.sections.HNavigationPart',
        'Rsd.hermit.sections.ImageNewsViewPart',
        'Rsd.hermit.sections.ListGroupViewPart',
        'Rsd.hermit.sections.ProductViewPart',
        'Rsd.hermit.sections.ProductItemViewPart',
        'Rsd.hermit.sections.PagingCollectionPart',
        'Rsd.hermit.sections.ScrollListPart',
        'Rsd.hermit.sections.ScrollTopPart',
        'Rsd.hermit.sections.SvgContentPart',
        'Rsd.hermit.sections.SitePathPart',
        'Rsd.hermit.sections.SlideImagePart',
        'Rsd.hermit.sections.TopInfoBarPart',
        'Rsd.hermit.sections.TabContainerViewPart',
    ],
    draggable:false,
    closeBtn:false,
    autoLoad: true,
    guider:true,
    height: '100%',
    width: '100%',
    header:{
        xtype: 'container',
        header: false,
        height: 60,
        space: 0,
        style: {
            display: 'flex',
            fontWeight: 600,
            backgroundColor: '#f0f8ff',
            cursor: "default"
        },
        layout: {
            type: 'hbox',
            align: 'center'
        },
        items: [ 
            {
                xtype: 'button',
                margin: '0 20 0 10',
                label: false,
                width:50,
                height:50,
                style:{ 
                    border:'1px red solid',
                    backgroundColor:'transparent',
                    boxShadow:'1px 1px 1px 0px grey'
                },
                text: '❌',
                handler:'btn_close'
            }, 
            {
                xtype: 'label',
                label: false,
                flex: 1,
                style:{
                    fontSize:'120%'
                },
                text: '页面模块布局',
            },
            {
                xtype: 'combobox',
                margin: '0 10 0 20',
                label: '操作模式',
                //readonly: true,
                //disabled: true,
                nullText: null,//不显示
                width: 250,
                height: 35,
                style:{
                    fontSize:'120%'
                },
                required:true,
                value: 'sort',
                onchange:'mode_change',
                dataSource: [
                    { text: "模块排序", value: 'sort' },
                    { text: "添加模块", value: 'add' },
                    { text: "删除模块", value: 'delete' } 
                ]
            },  
            {
                xtype: 'button',
                label: false,
                margin: '0 20 0 10',
                width:80,
                height:40,
                style:{
                    color:'#ffffff',
                    backgroundColor:'#1a6031fa',
                    boxShadow:'2px 2px 2px 2px grey'
                },
                text: '确 定',
                handler:'btn_ok'
            } 
        ]
    },
    layout: { type: 'hbox', align: 'center',content:'center center' },
    items: [
        {
            xtype: 'list', 
            label: false,
            draggable:false,
            itemDrag:{
                value:true,
                target:'item',
                tip:'拖动模块进行排序',
                //拖动对象本身事件
                //onDragStart:'block_onDragStart',
                //onDragEnd:'block_onDragEnd',
                onDrop:'block_onDrop' ,
                //过程对象事件
                onDragOver:'block_onDragOver',
                //onDragEnter:'block_onDragEnter',
                onDragLeave:'block_onDragLeave',
            },
            flex: 1,
            height:'100%',
            itemStyle:{
                margin:'45px 5% 45px 5%',
                width:'90%',
                height:'auto', 
                overflow:'visible',
                boxSizing:'border-box',
                border:'1px #0403033b solid',
                justifyContent:'center'
            },
            style:{ 
                zoom:'60%',
                // scale:'60%',
                // transformOrigin : 'top',
            },
            usingItemHover:'',
            layout:'none', 
            wrap:false,//禁止换行
            dataSource: [],
           
        },
        {
            xtype: 'list',
            label:{
                content:'模块列表',
                visible:false,
                height:60,
                space:0,
                style:{
                    fontWeight:600,
                    backgroundColor:'#3b8ed67a'
                }
            }, 
            width: '20%',
            height:'100%',
            style:{ 
            },
            draggable:false,
            itemDrag:{
                value:true,
                tip:'拖动模块到左侧区域',
                onDragStart:'new_block_onDragStart',
                onDragEnd:'new_block_onDragEnd',
            },
            itemStyle:{ 
                margin:'45px 10% 45px 10%',
                width:'80%', 
                minHeight:'300px',
                overflow:'visible',
                boxSizing:'border-box',
                border:'1px #201b1bba solid',
                boxShadow : '0px 5px 8px 5px grey',
                justifyContent:'center',
                zoom:'30%',
                //scale:'30%', 
                //transformOrigin : 'top'
            },
            layout:'none',
            wrap:false,//禁止换行
            dataSource: [],
            //hidden:true
        } 
    ],
    mode:'sort',//value of:add or sort or delete
    /**
    * 
    * @param {*} config 
    */
    constructor: function HermitPageLayouter(config) {
        config = config || {};
        this.apply(config); 
    },
    /**
     * 
     */
    load: function load(mode) {
  
        if(this.mode == mode)
        {
            return;
        } 
        this.mode = mode || this.mode||'sort';

        this.items[1].itemDrag.target = this.body.element;

        this.loadPageBlocks(this.mode);
       
        this.loadTplBlocks();
  
        this.callParent();

    },
    /**
     * 加载当前页面 模块
     */
    loadPageBlocks:function loadPageBlocks(mode)
    {
         var _btns = {
                position:'right',
                style:{
                    height:80,
                    width:80, 
                    display:'none'
                    //justifyContent:'start'
                },
                items:[
                     {
                        text:'X',
                        title:'删除该模块',
                        style:{
                            fontSize:'200%',
                            backgroundColor:'#fff',
                            color:'red',
                            padding:'0',
                            borderRadius:'30px',
                            lineHeight:60,
                            width:60,
                            height:60
                        },
                        handler:'btn_block_del'
                    } 
                ]
        }
       
        //console.log(this.pageConfig);
        var list = [];
        
        for(var i in this.pageConfig.content)
        {
            if(mode == 'add')
            {
                var _addBlock = {
                    id:'li_'+list.length,
                    xtype:'label',
                    label:false,
                    margin:'6 6 6 6',
                    index:list.length, 
                    width:'100%',
                    height:180, 
                    text:'拖动右侧模块到此处',  
                    style:{
                        letterSpacing:'5px',
                        fontSize:'250%',
                        boxSizing:'border-box',
                        border:'1px dotted #f10606'
                    } 
                };

                list.push(_addBlock);

                this.pageConfig.content[i]['liButtons'] = [];
                this.pageConfig.content[i]['click'] = '';
            } 
            if(mode == 'delete')
            {
                this.pageConfig.content[i]['liButtons'] = _btns;
                this.pageConfig.content[i]['click'] = 'block_selected';
            }  
             
            list.push(this.pageConfig.content[i]); 
        }

        if(this.pageConfig.content.length > 0 && mode == 'add')
        {
            var _addBlock = {
                    id:'li_'+list.length,
                    xtype:'label',
                    label:false,
                    margin:'6 6 6 6',
                    index:list.length, 
                    width:'100%',
                    height:180, 
                    text:'拖动右侧模块到此处',  
                    style:{
                         letterSpacing:'5px',
                        fontSize:'250%',
                        boxSizing:'border-box',
                        border:'1px dotted #f10606'
                    } 
            };
            list.push(_addBlock);
        }

        this.items[0].itemDrag = mode == 'sort';    
        this.items[0].loadData(list);


        if(mode == 'add')
        { 
            if(this.guider)
            {
                var x = (document.body.clientWidth - 1200)/2 + 90;
                setTimeout(function(){
                    Rsd.showTip('从右侧拖动模块到此处，可模块添加',250,60,x,20,'bottom',5000);
                },1000);
                setTimeout(function(){
                    Rsd.showTip('拖动模块到左侧添加区域,完成模块添加',300,60,document.body.clientWidth*0.65,50,'right',6000);
                },2000); 
            } 
        }
         if(mode == 'sort')
        {  
            if(this.guider)
            {
                var x = (document.body.clientWidth - 1200)/2 + 130;
                setTimeout(function(){
                    Rsd.showTip('拖动模块可进行位置排序',250,60,x,20,'bottom',5000);
                },1000);
                
            } 
        }
         if(mode == 'delete')
        {  
            if(this.guider)
            { 
                var x = (document.body.clientWidth - 1200)/2 + 130;
                setTimeout(function(){
                    Rsd.showTip('点击模块选择中状态下，点击删除按钮可删除模块',300,60,x+400,20,'bottom',6000);
                },2000);  
            } 
        }
    },
    /**
     * 加载 模块控件
     */
    loadTplBlocks:function loadTplBlocks()
    {
        //从 组件库 加载
        var list = [
                {
                    xtype: 'ads-view',
                    header:{
                        content:'图文模块:图片+html代码块+跳转链接+点击按钮',
                        position:'top',
                        height:60,
                        style:{
                            fontSize:'150%',
                            textAlign:'center',
                            lineHeight:60,
                            backgroundColor:'#b0b1af38',
                           
                        }
                    },
                    height:400,
                    width: '100%', 
                    dataSource: {
                        link: {
                            url: '',
                            target: '_self'
                        },
                        html: {
                            content: 'Box Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                            style: {
                                color: '#000',
                                fontSize: '150%',
                                width: '90%',
                                top: 90,
                                left: 50
                            }
                        },
                        button: {
                            text: 'BUY NOW',
                            style: {
                                top: '270px',
                                left: 300,
                                width: '80%',
                                textAlign: 'center',
                                backgroundColor:'red'
                                //color:'#fff'
                            }
                        },
                        image: {
                            position: 'left center',
                            size: 'contain',
                            src: 'https://mountainspring.com.cn/_nuxt/img1.d0f158ca.jpg',
                        }
                    }

                },
                {
                    xtype: 'collection',
                    label:{
                        content:'图文集合模块:展示一组多个图文模板；支持多行多列设置',
                        position:'top',
                        height:60,
                        style:{
                            fontSize:'150%',
                            textAlign:'center',
                            lineHeight:60,
                            backgroundColor:'#b0b1af38',
                           
                        }
                    },
                    height:'100%',
                    width: '100%',     
                    itemStyle:{ 
                        margin:'20px 0 0px 0',
                        justifyContent: 'center'
                    },   
                    columnCount:2,
                    itemXtype:'ads-view', 
                    dataSource:[
                        {
                            height:300, 
                            width:'80%',
                            dataSource:{
                                html:'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                image:{
                                    src:'https://img1.baidu.com/it/u=3181593724,3264993892&fm=253&app=138&f=JPEG?w=800&h=1062'
                                }
                            } 
                        },
                        {
                            height:300, 
                            width:'80%',
                            dataSource:{
                                html:'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                image:{
                                    src:'https://img1.baidu.com/it/u=3181593724,3264993892&fm=253&app=138&f=JPEG?w=800&h=1062'
                                }
                            }
                        },
                        {
                            height:300, 
                            width:'80%',
                            dataSource:{
                                html:'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                image:{
                                    src:'https://img2.baidu.com/it/u=803513621,2475111804&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1076'
                                }
                            }
                        },
                        {
                            height:300, 
                            width:'80%',
                            dataSource:{
                                html:'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                image:{
                                    src:'https://img2.baidu.com/it/u=803513621,2475111804&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1076'
                                }
                            }
                        }
                    ]
                },
                {
                    xtype: 'collection',
                    label:{
                        content:'产品集合模块:展示一组多个产品模板；支持多行多列设置',
                        position:'top',
                        height:60,
                        style:{
                            fontSize:'150%',
                            textAlign:'center',
                            lineHeight:60,
                            backgroundColor:'#b0b1af38',
                           
                        }
                    },
                    height:'100%',
                    width: '100%',     
                    itemStyle:{ 
                        margin:'20px 0 50px 0',
                        justifyContent: 'center'
                    },   
                    columnCount:4,
                    itemXtype:'product-item-view', 
                    dataSource:[
                        {
                            height: 400,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur.sunt in culpa qui officia deserun',
                                price: 99.99,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }

                        },
                        {
                            height: 200,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident',
                                price: 99.97,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        },
                        {
                            height: 400,
                            width: '80%',
                            dataSource: {
                                title: ' Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                price: 99.89,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        },
                        {
                            height: 300,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur. sunt in culpa qui officia deserun',
                                price: 99.59,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        }
                    ]
                },
                {
                    xtype: 'paging-collection', 
                    label:{
                        content:'产品集合模块:根据API数据源返回的数据，展示一组多个产品；支持多行多列设置,支持分页展示',
                        position:'top',
                        height:60,
                        style:{
                            fontSize:'150%',
                            textAlign:'center',
                            lineHeight:60,
                            backgroundColor:'#b0b1af38', 
                        }
                    },
                    height:'100%',
                    width: '100%',  
                    itemXtype:'product-item-view', 
                    dataSource: 'unapp.product.example'
                },
                {
                    xtype: 'collection',
                    label:{
                        content:'产品集合模块:展示一组多个产品模板；支持多行多列设置',
                        position:'top',
                        height:60,
                        style:{
                            fontSize:'150%',
                            textAlign:'center',
                            lineHeight:60,
                            backgroundColor:'#b0b1af38',
                           
                        }
                    },
                    height:'100%',
                    width: '100%',     
                    itemStyle:{ 
                        margin:'20px 0 0px 0',
                        justifyContent: 'center'
                    },   
                    columnCount:4,
                    itemXtype:'blog-item-view', 
                    dataSource:[
                        {
                            height: 400,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur.sunt in culpa qui officia deserun',
                                price: 99.99,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }

                        },
                        {
                            height: 200,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata non proident',
                                price: 99.97,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        },
                        {
                            height: 400,
                            width: '80%',
                            dataSource: {
                                title: ' Excepteur sint occaecat cupidata non proident, sunt in culpa qui officia deserun',
                                price: 99.89,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        },
                        {
                            height: 300,
                            width: '80%',
                            dataSource: {
                                title: 'Velit esse cillum dolore eu fugiat nulla pariatur. sunt in culpa qui officia deserun',
                                price: 99.59,
                                images: ['https://preview.qiantucdn.com/58pic/q9/0M/L8/Br/n51jelmz86doay7hxk2trvp03qs9fc4w_PIC2018.png!qt_w320']
                            }
                        }
                    ]
                }
        ];

        this.items[1].loadData(list);
    },
    /**
     * 
     * @param {*} sender 
     * @param {*} evt 
     */
    mode_change:function mode_change(sender,evt)
    {
        //console.log(sender.selectedItem.value,evt);
        
        this.loadPageBlocks(sender.selectedItem.value);
        this.mode = sender.selectedItem.value;
        
    }, 
    /**
     * 
     * @param {*} sender 
     * @param {*} evt 
     * @returns 
     */
    block_selected:function block_selected(sender,evt,cfg)
    {
         var me = this;
        //console.log(sender,evt);
        evt.preventDefault();
        evt.stopPropagation();
        var ele = evt.target;
        while(ele != null && (ele.id != sender.id || ele.tagName.toLowerCase() != 'li'))
        {
            ele = ele.parentNode;
        }
        
        if(ele != null && ele.tagName.toLowerCase() == 'li')
        {    
            for(var i=0;i < ele.parentNode.childNodes.length;i++)
            {   
                ele.parentNode.childNodes[i].style.boxShadow='';
                ele.parentNode.childNodes[i].style.scale= 1; 
                //隐藏buttons
                ele.parentNode.childNodes[i].childNodes[0].style.display= 'none';
            }
            ele.style.boxShadow = '15px 15px 25px 25px grey';
            ele.style.scale= 1.05; 
            //显示buttons
            ele.childNodes[0].style.display= 'flex';
        } 
        //Rsd.popup('选择模块（section）:' + sender.id);
        return false;
    }, 
    /**
     * 
     * @param {*} sender 
     * @param {*} cfg 
     * @param {*} evt 
     */
    btn_block_del:function btn_block_del(sender,evt,cfg)
    { 
        console.log('btn_block_del',arguments);
        evt.target.parentNode.parentNode.remove();
        Rsd.popup('模块已删除');
    },
    block_onDragEnter:function block_onDragEnter(sender,evt)
    {
        console.log('block_onDragEnter',sender,evt.target.id,evt); 
    },
    block_onDragLeave:function block_onDragLeave(sender,evt)
    {  
        var me = this;
        var target_li = sender; 
        //console.log('block_onDragLeave',sender.id,target_li.id,evt);  

        if (me.___current_li === target_li.id) {
            setTimeout(function () {
                target_li.style.boxShadow = '';
                target_li.style.scale = 1;
                me.___current_li = null;
            }, 200);
        }
       
    },
    /**
     * 
     */
    block_onDragOver:function block_onDragOver(sender,evt)
    { 
         var me = this;
        var target_li = sender; 
        //console.log('block_onDragOver',sender,target_li.id,evt);  
        
        //判断拖动对象 和 target_li 是否是 同一个对象
        if(target_li.getAttribute('is_dragging')==='true')
        {
            return;
        }
 
        if(this.mode == 'sort')
        {
            me.___current_li = target_li.id;

            setTimeout(function(){
                //延时 
                if(me.___current_li)
                {
                    target_li.style.boxShadow = '15px 15px 25px 25px grey';
                    target_li.style.scale = 1.05; 
                }
                
            },200);
             
            return;
        }
        
        var index = Number.parseInt(target_li.id.substring(3).replace('_ctrl'))%2;

        if ((index == 0 && this.mode == 'add')) {
            //进入目标区域
            //console.log('进入目标区域', sender,target_li); 
             target_li.style.boxShadow = '15px 15px 25px 25px grey';
             target_li.style.scale = 1.05;  
            return;
        }
 
    },
    /**
     * 
     * @param {*} sender 
     * @param {*} evt 
     */
    block_onDrop:function block_onDrop(sender,evt,data)
    { 
         var me = this;
        //console.log('block_onDrop',sender,evt); 
        var target_li = sender;//释放位置 所在控件
        target_li.style.boxShadow = '';
        target_li.style.scale= 1;  
        //var s_index = this.pageConfig.content.findIndex((p)=>p.id == sender.id);
        //var t_index = this.pageConfig.content.findIndex((p)=>p.id == target_li.id);

        //识别 拖动对象
        var list = this.items[0].ctrl.element;
        var source_li = Rsd.select(list,'li[id='+data.id+']')[0]; 
        console.log('识别 拖动对象',source_li);
        if(this.mode =='add')
        {
            var ds_list = this.pageConfig.content;
            var index = Number.parseInt(evt.target.id.substring(3).replace('_ctrl'))/2;
            //console.log(evt.target.id.substring(3),index);
            ds_list.splice(index, 0, data);
             
            this.loadPageBlocks(this.mode);
            //调整数据源 
            console.log('添加:调整数据源');// 
            //this.pageConfig.content[t_index] =  this.pageConfig.content[s_index];
        }

       if(this.mode =='sort')
        {  
            //console.log('block_onDrop',source_li.offsetTop + ' to ' + target_li.offsetTop); 
            if(target_li.offsetTop < source_li.offsetTop)
            {  
                //上移： 插入到目标对象之前 
                list.insertBefore(source_li,target_li); 
                //console.log('上移：'+source_li.id + '到' + target_li.id + '之前',target_li.parentNode == source_li.parentNode,source_li.parentNode==list);
            } 
            else
            {
                //下移： 插入到目标对象之后(即：目标对象 下一个相邻对象之前)
                if(target_li.nextSibling)
                {
                    list.insertBefore(source_li,target_li.nextSibling); 
                }
                else
                {
                    list.appendChild(source_li); 
                }
                //console.log('下移：'+source_li.id + '到' + target_li.id + '之后',target_li.parentNode == source_li.parentNode,source_li.parentNode==list);
            }
           
            //调整数据源 
            console.log('排序:调整数据源');// 
            //this.pageConfig.content[t_index] =  this.pageConfig.content[s_index]; 
        }
         
    },
    /**
     * 
     * @param {*} sender 
     * @param {*} evt 
     */
    new_block_onDragStart:function new_block_onDragStart(sender,evt)
    { 
        //console.log('new_block_onDragStart',sender,evt.target.id,evt);
        if(this.mode != 'add')
        {
            evt.dataTransfer.effectAllowed = 'none';
            Rsd.popup('非添加模式下，操作无效');
        }
      
        //添加模式下 拖动时 缩放
       
    },
    new_block_onDragEnd:function new_block_onDragEnd(sender,evt)
    { 
        //console.log('block_onDragEnd',sender,evt.target.id,evt);
        //添加模式下 拖动结束 还原缩放
        //sender.style.transform = '';
    },
     /**
     * 
     */
    btn_close:function btn_close()
    {
        this.close();
    },
    /**
     * 
     */
    btn_ok:function btn_ok()
    {
         this.close();
    }
});